﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace TypeBuilderFx.Core
{
    /// <summary>In-memory implementation of <see cref="ITypeEmitterCache"/>.</summary>
    public class InMemoryTypeEmitterCache : TypeEmitterCacheBase
    {
        private readonly object _syncObject = new object();
        private readonly ModuleBuilderExtender _moduleBuilder = CreateModuleBuilder();

        /// <summary>Nothing specific to do.</summary>
        protected override void OnDispose()
        {
        }

        /// <summary>Returns an in-memory module builder.</summary>
        protected override ModuleBuilderExtender ModuleBuilder
        {
            get { return _moduleBuilder; }
        }

        private static ModuleBuilderExtender CreateModuleBuilder()
        {
            string assemblyName = string.Concat(typeof(InMemoryTypeEmitterCache).Name, "_", GetUniqueString());
            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                new AssemblyName(assemblyName),
                AssemblyBuilderAccess.Run);

            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName, true);

            return new ModuleBuilderExtender(moduleBuilder);
        }
    }
}